#include "mini_crt.h"

int main(int argc, char* argv[]) {
    int i = 0;
    FILE* fp = NULL;
    char** v = NULL;

    v = malloc(argc * sizeof(char*));

    printf("%s:%d test malloc and args:\n", __FILE__, __LINE__);
    for(i = 0; i < argc; ++i) {
        int l = strlen(argv[i]) + 1;
        v[i] = malloc(l);
        strcpy(v[i], argv[i]);
        printf("%s:%d argv[%d]:%s\n", __FILE__, __LINE__, i, v[i]);
    }

    printf("%s:%d test io(file-for write):\n", __FILE__, __LINE__);
    fp = fopen("test.txt", "w");
    for(i = 0; i < argc; ++i) {
        int len = strlen(v[i]);
        if(1 != fwrite(&len, sizeof(int), 1, fp)) {
            printf("Write [len] err:%d\n", len);
            fclose(fp);
            exit(-1);
        }
        if(1 != fwrite(v[i], len, 1, fp)) {
            printf("Write err:%s\n", v[i]);
            fclose(fp);
            exit(-1);
        }
    }
    fclose(fp);

    printf("%s:%d test io(file-for read):\n", __FILE__, __LINE__);
    fp = fopen("test.txt", "r");
    for(i = 0; i < argc; ++i) {
        int len = 0;
        char* buf = NULL;

        if(1 != fread(&len, sizeof(int), 1, fp)) {
            printf("[ERR] %s:%d fread err\n", __FILE__, __LINE__);
        }
        buf = malloc(len + 1);
        fread(buf, len, 1, fp);
        buf[len] = '\0';
        printf("%s:%d v[%d] len=%d, ->%s\n", __FILE__, __LINE__, i, len, buf);
        free(buf);
        free(v[i]);
    }
    fclose(fp);
    free(v);
	return 0;
}
